package com.bee.web.handle;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.bee.web.annotation.ValidateToken;
import com.bee.web.token.TokenManager;
import com.bee.web.util.FastJsonUtil;
import com.bee.web.util.WebUtil;
import com.bee.web.vo.BaseVo;

/**
 * @author liuzy
 * @version 2015年6月12日
 */
public class ControllerHandle extends HandlerInterceptorAdapter {

    private Logger logger = Logger.getLogger(ControllerHandle.class);

    @Autowired
    private TokenManager tokenManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("[请求]" + WebUtil.getRequestURIWithParam(request));
//        logger.info("[库克]" + WebUtil.readCookies(request));
        Method method = ((HandlerMethod) handler).getMethod();
        if (method.isAnnotationPresent(ValidateToken.class)) {
//            String token = WebUtil.getCookieValueByName(request, "SESSIONTOKEN");
            String token = request.getParameter("sid");
            if (tokenManager.isToken(token)) {
                logger.info("[令牌有效]");
                return true;
            } else {
                logger.info("[令牌无效]");
                this.reply(response, new BaseVo("ERROR", "已过期，请重新登陆"));
                return false;
            }
        }
        return true;
    }

    private void reply(HttpServletResponse response, BaseVo vo) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            String json = FastJsonUtil.toJSON(vo);
            response.getWriter().write(json);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
